//
//  CartManager.m
//  AppleCilent
//
//  Created by Nail Sharipov on 06/04/14.
//  Copyright (c) 2014 Nail Sharipov. All rights reserved.
//

#import "CartManager.h"
#import "DataRequest.h"
#import "MainProperties.h"

@implementation CartManager
{
    NSMutableDictionary* orderList;
}

+ (CartManager*)getInstance
{
    static CartManager* instance;
    
    @synchronized(self)
    {
        if (!instance)
            instance = [[CartManager alloc] init];
        return instance;
    }
}

- (id)init
{
    self = [super init];
    orderList = [[NSMutableDictionary alloc] init];
    return self;
}

- (CartOrder*) getOrder: (GoodsDomain*) goods
{
    NSString* key = [NSString stringWithFormat:@"%i",[goods getId]];
    CartOrder* order = (CartOrder*)[orderList objectForKey:key];
    if (order == nil) {
        order = [[CartOrder alloc] init:goods];
        [orderList setValue:order forKey:key];
    }
    
    NSLog(@"Get %@ with quantity %i", [goods getName], [order getQuantity]);
    
    return  order;
}

- (NSArray*) getOrderList
{
    NSMutableArray* list = [[NSMutableArray alloc] init];
    for (CartOrder* order in [orderList allValues]) {
        if ([order getQuantity] > 0) {
            [list addObject:order];
        }
    }
    return [[NSArray alloc] initWithArray:list];
}

- (float) getTotalCost
{
    float total = 0.0f;
    for (CartOrder* order in [orderList allValues]) {
        int quantity = [order getQuantity];
        float price = [[order getGoods] getPrice];
        total = total + price * quantity;
    }
    return total;
}

- (void) sendOrder {
    NSString* json = @"[";
    NSArray* list = [self getOrderList];
    int n = [list count];
    int i = 0;
    for (CartOrder* order in list) {
        i++;
        json = [json stringByAppendingString:[order toJSON]];
        if (i != n) {
            json = [json stringByAppendingString:@","];
        }
    }
    json = [json stringByAppendingString:@"]"];
    NSString* params = [NSString stringWithFormat:@"order=%@", json];
    
    NSString* rootUrl = [[MainProperties getInstance] getRootUrl];
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat: @"%@addOrder", rootUrl]];
    DataRequest* request = [[DataRequest alloc] init];
    [request sendToURL:url parameters:params onReady:^(NSMutableData* data)
     {
         NSLog(@"data sended");
         
     }];
}


@end
